package com.sanhuo.idms.service;

import com.sanhuo.idms.bo.PersonalUpdateBO;
import com.sanhuo.idms.dao.RepairPersonalMapper;
import com.sanhuo.idms.entity.RepairPersonal;
import com.sanhuo.idms.vo.RepairPageVO;
import com.sanhuo.idms.vo.RepairPersonalVO;
import com.sanhuo.idms.vo.TaskNumVO;
import com.sanhuo.lib.ExceptionUtil;
import com.sanhuo.security.UserVo;
import com.sanhuo.security.entity.User;
import com.sanhuo.security.service.UserService;
import com.sanhuo.triild.Basic.BaseMapper;
import com.sanhuo.triild.Basic.BaseService;
import com.sanhuo.triild.annotation.MapperWire;
import com.sanhuo.triild.page.Page;
import com.sanhuo.triild.page.PageSearch;
import com.sanhuo.utils.basic.BeanUtil;
import com.sanhuo.utils.basic.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service
public class RepairPersonalService extends BaseService<RepairPersonal> {
    @MapperWire
    private RepairPersonalMapper repairPersonalMapper;
    @Autowired
    private RepairService repairService;
    @Autowired
    private RepairTaskService repairTaskService;
    @Autowired
    private UserService userService;

    @Override
    public BaseMapper<RepairPersonal> getBaseMapper() {
        return repairPersonalMapper;
    }

    public Page<RepairPersonalVO> list(PageSearch pageSearch) {
        pageSearch.setOrderBy(" repair_personal.updateTime desc");
        return repairPersonalMapper.list(pageSearch);
    }

    public RepairPersonalVO detailVO(String id) {
        RepairPersonalVO result = repairPersonalMapper.detailVO(id);
        List<String> taskIds = repairTaskService.findRepairIds(id);
        if (!CollectionUtil.isEmpty(taskIds)) {
            List<RepairPageVO> tasks = repairService.findByIds(taskIds);
            if (!CollectionUtil.isEmpty(tasks)) {
                result.setTask(tasks);
            }
        }
        return result;
    }

    public void update(final UserVo user, PersonalUpdateBO bo) throws IllegalAccessException {
        RepairPersonal repairPersonal = findById(bo.getId());
        ExceptionUtil.throwException(BeanUtil.isNull(repairPersonal), "不存在此维修人员数据");
        User personal = userService.findById(bo.getId());
        BeanUtil.copyBean(bo, personal);
        personal.updatorInfo(user);
        userService.update(personal);
        BeanUtil.copyBean(bo, repairPersonal);
        repairPersonal.updatorInfo(user);
        update(repairPersonal);
    }

    public Page<RepairPageVO> myTask(final UserVo user, PageSearch pageSearch) {
        return repairPersonalMapper.mytask(user.getId(), pageSearch);
    }

    public TaskNumVO taskNum(String id) {
        return repairPersonalMapper.countTaskNum(id);
    }

}
